
define(function(require, exports, module) {
    "use strict";

    var result = {};

    var Defer = require("../plugins/defer/defer"),
        CONFIG = require("./config");


    // 获取页面参数
    result.getQueryParms = function(name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
            return unescape(r[2]);
        }
        return null;
    }

    // 改变时间格式
    result.changeTime = function(str, format) {
        if (!str) return "";
        if (!format) {
            format = "yyyy-mm-dd"; //  hh:ii
        };
        var date;
        if (typeof str === "string") {
            date = new Date(str.replace(/-/g, "/").replace(/T/g, " ").replace(/\+.*$/g, ""));
        } else {
            date = str;
        }

        var objForReplace = {
            y: function(length) {
                length = length < 2 ? 4 : length;
                return date.getFullYear().toString().slice(4 - length, 4);
            },
            m: function() {
                var s = date.getMonth() + 1 + "";
                if (s.length < 2) {
                    s = "0" + s;
                }
                return s;
            },
            d: function() {
                var s = date.getDate() + "";
                if (s.length < 2) {
                    s = "0" + s;
                }
                return s;
            },
            h: function() {
                var s = date.getHours() + "";
                if (s.length < 2) {
                    s = "0" + s;
                }
                return s;
            },
            i: function() {
                var s = date.getMinutes() + "";
                if (s.length < 2) {
                    s = "0" + s;
                }
                return s
            },
            s: function() {
                var s = date.getSeconds() + "";
                if (s.length < 2) {
                    s = "0" + s;
                }
                return s;
            },
            w: function() {
                var s = date.getDay();
                return "周" + "日一二三四五六".charAt(s);
            },
            p: function() {
                var s = date.getDay();
                return "6012345".charAt(s);;
            }
        };
        var reg = /y+|m+|d+|h+|i+|s+|w+|p+/gi
        var rtStr = format.replace(reg, function(r) {
            var len = r.length;
            var type = r.charAt(0);
            return objForReplace[type](len);
        });

        return rtStr;
    }

    // 获取当前日期或设置
    result.curDate = function (setMonth) {
        var now = new Date(),
            year = now.getFullYear(),       // 年
            month = now.getMonth() + 1,     // 月
            day = now.getDate(),            // 日
            date;

        // 当前时间减去设置月份
        if (setMonth) {
            month = month - parseInt(setMonth);
            if (month < 0) {
                year = year - 1;
                month = month + 12;
            }
        }

        date = year + "-";

        if (month < 10) { date += "0"; }

        date += month + "-";

        if (day < 10) { date += "0";}

        date += day;

        return date;
    }

    // 登录态
    var _dev = window.localStorage.getItem('_dev');

    // ajax
    result.ajax = function(url, jsonParam, obj) {

        var defer = new Defer(),
            obj = obj || {}, // ajax 其他参数
            cacheResult, // 已缓存结果
            ajaxJquery,
            option = {};

        option.url = CONFIG.baseUrl + url;
        option.type = obj.type || "get";
        option.data = jsonParam || {};
        obj.upload = obj.upload || false;

        // 上线自动注释掉
        if(_dev){option.data._dev = _dev;}

        // 临时缓存结果
        if (obj.cache && (cacheResult = _session.getItem(JSON.stringify(option))) ) {
            defer.resolve($.extend(true, {}, JSON.parse(cacheResult)));
        } else {
            ajaxJquery = $.ajax({
                url: option.url,
                timeout: CONFIG.ajaxtimeout,
                type: option.type,
                data: option.data,
                contentType: obj.upload ? false : 'application/x-www-form-urlencoded; charset=UTF-8',
                processData: obj.upload ? false : true,
                dataType: "json",
                async: true,
                success: function(json) {
                    // console.log(json);
                    if (json) {
                        if (obj.returnAll) {
                            defer.resolve(json);
                            return;
                        }
                        if (json.code === 0) {
                            defer.resolve(json);
                        } else if (json.code === 18113){
                            // 未登录
                            window.location.href = "../login.html";
                            defer.reject(json);
                        } else {
                            defer.reject(json);
                            result.alert(json.msg);
                            // console.error("业务异常：" + url);
                            // console.log(json);
                        }
                    } else {
                        defer.reject();
                        result.alert("解析异常");
                    }
                },
                error: function(xhr, error) {
                    if (error === "abort") return;

                    if (error === "parsererror") {
                        defer.reject();
                        result.alert("解析异常");
                    } else {
                        // if (error !== "timeout") {}
                        // console.error("请求异常：" + url);
                        result.alert("网络异常");
                        defer.reject();
                    }
                }
            });

        }

        defer.abort = function() {
            ajaxJquery && ajaxJquery.abort();
            // result.alert("取消请求");
            defer.reject();
        }


        return defer;
    };
    // 去除前后空格
    result.trim = function(str) {
        str = (typeof str === "string") ? str.replace(/(^\s*)|(\s*$)/g, "") : str
        return str
    }

    // 提示
    result.alert = function(mess, time) {
        let $tool = $("#J__m_tooltips")
        let defer = new Defer()
        if ($tool.length) {
            $tool.find(".tooltip-text").html(mess)
        } else {
            $tool = $('<div id="J__m_tooltips" class="m_tooltips none"/>')
            $('<div class="tooltip-text tooltip-content"/>').html(mess).appendTo($tool)
            $tool.appendTo('body')
        }

        $tool.removeClass("none")
        $tool.get(0).offsetHeight
        $tool.addClass("on")

        time = time || 2500
        setTimeout(function() {
            $tool.removeClass("on")
            $tool.addClass("none")
            defer.resolve()
        }, time)
        return defer
    }
    // loading
    result.loading = {
        $load: $("#J_m_loading"),
        show (mess,type) {
            mess = (mess ? mess : '加载中')
            if (this.$load.length)
                this.$load.find(".J__loadingmess").html(mess)
            else
                this.$load = $('<div id="J__loadingF" class="m_loading"/>')
                this.$load.html('<div>'+
                    '<div class="loading__img"></div>'+
                    '<div class="loading__mess"><span class="J__loadingmess">'+
                    mess +
                    '</span><span class="dotloading"></span></div></div>'
                ).appendTo('body')
            this.$load.addClass("on")
        },
        hide () {
            this.$load.removeClass("on full");
        }
    }

    module.exports = result;
});
